const { exec } = require('../db/mysql');

const getBlogList = (keyword, author) => {
  let sql = 'select * from blogs where 1=1 ';
  if (author) {
    sql += `and author='${author}' `
  }
  if (keyword) {
    sql += `and title like '%${keyword}%' `
  }
  sql += 'order by createtime desc;'

  return exec(sql)
}

const getDetailById = id => {
  const sql = `select * from blogs where id='${id}'`;
  return exec(sql).then(rows => {
    return rows[0]
  });
}

const newBlog = (blogData = {}) => {
  // 新建博客对象,包含标题,内容
  const createtime = Date.now();
  const sql = `insert into blogs (title, content, createtime, author)
               values ('${blogData.title}', '${blogData.content}', ${createtime}, '${blogData.author}')`;
  return exec(sql).then(insertData => {
    return {
      id: insertData.insertId
    };
  });
}
// 更新
const updateBlog = (id, blogData = {}) => {
  const { content, title } = blogData;
  const createtime = Date.now();
  console.log(content, title, createtime)
  let sql = `update blogs set content='${content}',title='${title}',createtime=${createtime} where id='${id}'`;
  return exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true;
    }
    return false;
  });
}

//删除
const deleteBlog = (id, author) => {
  const sql = `delete from blogs where id='${id}' and author='${author}'`;
  return exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true;
    }
    return false;
  })
}

module.exports = {
  getBlogList,
  getDetailById,
  newBlog,
  updateBlog,
  deleteBlog
}
